package com.egghiro.framework.j2se.game.model.shape;

public class Matrix2D {

    public SVector2D col1 = new SVector2D();

    public SVector2D col2 = new SVector2D();

    public Matrix2D() {
    }

    public Matrix2D(double angle) {
        double c = Math.cos(angle);
        double s = Math.sin(angle);
        col1.x = c;
        col2.x = -s;
        col1.y = s;
        col2.y = c;
    }

    public Matrix2D(SVector2D col1, SVector2D col2) {
        this.col1.reset(col1);
        this.col2.reset(col2);
    }

    public SVector2D multiply(SVector2D vec) {
        double x = col1.x * vec.x + col2.x * vec.y;
        double y = col1.y * vec.x + col2.y * vec.y;
        return new SVector2D(x, y);
    }

    public Matrix2D transpose() {
        return new Matrix2D(new SVector2D(col1.x, col2.x), new SVector2D(col1.y, col2.y));
    }

    public Matrix2D invert() {
        double a = col1.x, b = col2.x, c = col1.y, d = col2.y;
        Matrix2D m2d = new Matrix2D();
        double det = a * d - b * c;
        if (det == 0.0f) {
            throw new RuntimeException("det == 0.0");
        }

        det = 1.0f / det;
        m2d.col1.x = det * d;
        m2d.col2.x = -det * b;
        m2d.col1.y = -det * c;
        m2d.col2.y = det * a;
        return m2d;
    }

}
